package org.gl.training.gwt.server.service;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;

import org.gl.training.gwt.client.service.TaskService;
import org.gl.training.gwt.server.utils.DailyPlanVOUtils;
import org.gl.training.gwt.server.utils.TaskVOUtils;
import org.gl.training.gwt.shared.model.DailyPlanVO;
import org.gl.training.gwt.shared.model.TaskVO;
import org.gl.training.planner.dao.DailyPlanDao;
import org.gl.training.planner.dao.TaskDao;
import org.gl.training.planner.dao.UserDao;
import org.gl.training.planner.model.DailyPlan;
import org.gl.training.planner.model.Task;
import org.gl.training.planner.model.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TaskServiceImpl extends RemoteServiceServlet implements
		TaskService {

	@EJB
	private DailyPlanDao dailyPlanDao;

	@EJB
	private UserDao userDao;

	@EJB
	private TaskDao taskDao;

	private static final long serialVersionUID = 8415957383778053529L;

	@Override
	public DailyPlanVO getDailyPlan(Integer userId, Date date) {
		DailyPlan dailyPlan = dailyPlanDao.getDailyPlan(userId, date);

		if (dailyPlan == null) {
			dailyPlan = createDailyPlan(userId, date);
		}

		DailyPlanVO dailyPlanVO = DailyPlanVOUtils.getDailyPlanVO(dailyPlan);
		return dailyPlanVO;
	}

	protected DailyPlan createDailyPlan(Integer userId, Date date) {
		User user = userDao.find(userId);

		DailyPlan dailyPlan = new DailyPlan();
		dailyPlan.setDate(date);
		dailyPlan.setUser(user);

		return dailyPlanDao.save(dailyPlan);
	}

	@Override
	public void saveTask(TaskVO taskVO) {
		Task task = TaskVOUtils.getTask(taskVO);
		DailyPlan dailyPlan = getDailyPlan(taskVO.getDailyPlanVO());
		task.setDailyPlan(dailyPlan);
		taskDao.save(task);
	}

	@Override
	public void delete(List<Integer> idList) {
		for (int id : idList) {
			taskDao.delete(id);
		}
	}

	protected DailyPlan getDailyPlan(DailyPlanVO dailyPlanVO) {
		return dailyPlanDao.findDailyPlan(dailyPlanVO.getId());
	}
}
